<template>
  <div class="chat_room" @click="eventClick($event)">
    <div class="bg">
      <img src="https://pic.rmb.bdstatic.com/bjh/f30968641a6433f315533c027f345baa.jpeg" alt />
    </div>
    <div class="container">
      <!-- 个人信息 -->
      <div class="user_box">
        <div class="avatar">
          <div class="img_box">
            <img class="avatar_url img" :src="getUser.photo" alt />
          </div>
        </div>
        <div class="prefix_class user_info" v-if="show">
          <div class="prefix_class img_box">
            <img class="prefix_class img avatar_url" :src="getUser.photo" alt />
          </div>
          <div class="prefix_class other">
            <span class="prefix_class">{{ getUser.userName }}</span>
          </div>
        </div>
        <div class="tab_box">
          <div @click="tab = 'chat'">
            <span class="iconfont icon-liaotian1" :class="tab == 'chat' ? 'active' : ''"></span>
          </div>
          <div @click="tab = 'users'">
            <span class="iconfont icon-tongxunlu1" :class="tab == 'users' ? 'active' : ''"></span>
          </div>
        </div>
        <div class="bottom">
          <div>
            <span class="iconfont icon-xuzhi" @click="open"></span>
          </div>
          <div>
            <span class="iconfont icon-baseline-library_mus" @click="goMusic"></span>
          </div>
        </div>
      </div>
      <!-- 用户列表 -->
      <div class="user-list">
        <div class="search_box">
          <!-- <el-input
            placeholder="搜索"
            suffix-icon="el-icon-search"
            v-model="keyword"
          >
          </el-input>-->
          <span>{{ tab == "chat" ? "会话" : "联系人" }}</span>
        </div>
        <div class="scroll_box">
          <my-scroll>
            <div v-if="tab == 'chat'">
              <ul>
                <li class="user" @click="changeChat('group', {})">
                  <div class="avatar">
                    <img src="./images/group2.png" alt />
                    <div class="mess_icon"></div>
                  </div>

                  <div class="info_box">
                    <div class="info">
                      <span>群聊</span>
                      <span v-if="getGroupChat.length > 0">
                        {{
                        getGroupChat[getGroupChat.length - 1].date
                        | chatDateFormate
                        }}
                      </span>
                    </div>
                    <div class="msg" v-if="getGroupChat.length > 0">
                      {{
                      getGroupChat[getGroupChat.length - 1].name +
                      ":" +
                      (getGroupChat[getGroupChat.length - 1].type == "text"
                      ? getGroupChat[getGroupChat.length - 1].message
                      : "图片")
                      }}
                    </div>
                  </div>
                </li>
                <li
                  class="user"
                  @click="changeChat('private', item)"
                  v-for="(item, index) in dialogue"
                  :key="index"
                >
                  <div class="avatar">
                    <img :src="item.photo" alt />
                    <span v-if="item.unRead" class="mess_icon"></span>
                  </div>
                  <div class="info_box">
                    <div class="info">
                      <span>{{ item.userName }}</span>
                      <span>{{ item.date | chatDateFormate }}</span>
                    </div>
                    <div class="msg">{{ item.type == "text" ? item.message : "图片" }}</div>
                  </div>
                </li>
              </ul>
            </div>
            <div v-else>
              <ul>
                <li class="user" @click="changeChat('group', {})">
                  <div class="avatar">
                    <img src="./images/group2.png" alt />
                  </div>
                  <div class="info_box">群聊</div>
                </li>
              </ul>
              <div class="grouping" v-for="(value, key, index) in userlist" :key="index">
                <div class="group_title" v-if="value.length > 0">{{ groupName[key] }}</div>
                <template v-if="value.length > 0">
                  <div
                    class="group_item"
                    v-for="item in value"
                    :key="'users' + item.account"
                    :class="'prefix' + item.account"
                    @click="changeChat('private', item)"
                    @contextmenu.prevent="Menu($event, item)"
                  >
                    <span class="avatar" :class="'prefix' + item.account">
                      <img :src="item.photo" alt />
                    </span>
                    <div class="other" :class="'prefix' + item.account">
                      <span class="name" :class="'prefix' + item.account">
                        {{
                        item.userName
                        }}
                      </span>
                      <span
                        class="landing_time"
                        :class="'prefix' + item.account"
                      >最近登陆：{{ item.LandingTime | chatDateFormate }}</span>
                    </div>
                  </div>
                </template>
              </div>
            </div>
          </my-scroll>
        </div>
      </div>

      <!-- 聊天主窗口 -->
      <div class="box">
        <!-- 聊天窗口头部 -->
        <div class="menu">
          <div @click="close">
            <span class="iconfont icon-close"></span>
          </div>
        </div>
        <div class="box-hd">
          <div v-if="chatID.chatType == 'private'">{{ chatID.user.userName }}</div>
          <div id="userCount" v-else>群聊（{{ getOnlineUsers.length }}人在线）</div>
        </div>

        <!-- 聊天窗口主体区域 -->
        <div class="box-bd">
          <my-scroll ref="chatScroll">
            <!-- id="box-bd" -->
            <!-- <div>
              <div class="system">
                <p class="message_system">
                  <span class="content">"往事随风"邀请你和"Boy"加入了群聊</span>
                </p>
              </div>
              <div class="message-box">
                <div class="my message">
                  <img class="avatar" src="/images/2.png" alt="" />
                  <div class="content">
                    <div class="bubble">
                      <div class="bubble_cont">在干嘛</div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="message-box">
                <div class="other message">
                  <img class="avatar" src="/images/5.png" alt="" />
                  <div class="content">
                    <div class="nickname">小美</div>
                    <div class="bubble">
                      <div class="bubble_cont">吃饭</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>-->
            <div v-if="chatID.chatType == 'group'">
              <div style="paddingTop:10px" v-for="(item, index) in getGroupChat" :key="index">
                <div class="date" v-if="item.showTime">{{ item.date | chatDateFormate }}</div>
                <div class="system" v-if="item.account == 0">
                  <p class="message_system">
                    <span class="content">{{ item.message }}</span>
                  </p>
                </div>
                <div class="message-box" v-else-if="item.account == getUser.account">
                  <div class="my message">
                    <img class="avatar" :src="item.photo" alt />
                    <div class="content">
                      <div class="bubble">
                        <div class="bubble_cont" v-if="item.type == 'text'">{{ item.message }}</div>
                        <div class="bubble_cont" v-else>
                          <img :src="item.message" />
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="message-box" v-else>
                  <div class="other message">
                    <img class="avatar" :src="item.photo" alt />
                    <div class="content">
                      <div class="nickname">
                        <span>{{ item.name }}</span>
                        <span v-if="item.isAdmin" class="blog">博主</span>
                      </div>
                      <div class="bubble">
                        <div class="bubble_cont" v-if="item.type == 'text'">{{ item.message }}</div>
                        <div class="bubble_cont" v-else>
                          <img :src="item.message" />
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div v-else>
              <template v-for="(item, index) in privateChat">
                <div class="message-box" v-if="item.account == getUser.account" :key="index">
                  <div class="date" v-if="item.showTime">{{ item.date | chatDateFormate }}</div>
                  <div class="my message">
                    <img class="avatar" :src="getUser.photo" alt />
                    <div class="content">
                      <div class="bubble">
                        <div class="bubble_cont" v-if="item.type == 'text'">{{ item.message }}</div>
                        <div class="bubble_cont" v-else>
                          <img :src="item.message" />
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="message-box" v-else :key="index">
                  <div class="date" v-if="item.showTime">{{ item.date | chatDateFormate }}</div>
                  <div class="other message">
                    <img class="avatar" :src="chatID.user.photo" alt />
                    <div class="content">
                      <div class="bubble">
                        <div class="bubble_cont" v-if="item.type == 'text'">{{ item.message }}</div>
                        <div class="bubble_cont" v-else>
                          <img :src="item.message" />
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </template>
            </div>
          </my-scroll>
        </div>

        <!-- 聊天窗口底部区域 -->
        <div class="box-ft">
          <!-- 工具栏 -->
          <div class="toolbar">
            <a href="javascript:;" title="表情" class="face" @click="showEmoji = !showEmoji"></a>
            <a href="javascript:;" title="截屏" class="screen-cut"></a>
            <a href="javascript:;" title="图片" class="file">
              <label for="file"></label>
              <input
                type="file"
                id="file"
                accept="image/*"
                @change="selectFile($event)"
                style="display: none;"
              />
            </a>
          </div>
          <emoji class="emoji" :page="type" @addEmoji="appendEmoji" v-show="showEmoji"></emoji>
          <!-- 内容输入区域 -->
          <div class="content">
            <!-- div添加一个属性：contenteditable -->
            <!-- <my-scroll>
              <div class="text" id="content" contenteditable></div>
            </my-scroll>-->
            <el-input
              id="msg_input"
              type="textarea"
              v-model="textarea"
              maxlength="90"
              show-word-limit
              @keydown.native="listen($event)"
            ></el-input>
          </div>
          <!-- 发送按钮 -->
          <div class="action">
            <a class="btn-send" id="btn-send" href="javascript:;" @click="send">发送 Enter</a>
          </div>
        </div>
      </div>
    </div>
    <div class="mouse_menu" v-if="showMenu" :style="{ left, top }">
      <span v-if="!selectItem.mute" @click="mute">禁言</span>
      <span v-else @click="mute">取消禁言</span>
    </div>
    <div class="attention" v-if="attention">
      <div class="att_bg" @click="attention = false">
        <div class="att_box">
          <div class="att_title">用户须知</div>
          <div class="att_content">
            <span>1：网站暂时不支持图片信息发送</span>
            <span>2：暂不开放用户之间私聊，仅开放用户与博主之间私聊</span>
            <span>3：请用户自觉遵守相关法律法规</span>
            <span>4：不得利用本站传播不良信息</span>
            <span>5：用户若有违规行为，本站将删除违法内容、目录，断开链接，注销其用户帐号</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Emoji from '../../components/chatEmoji/emoji'
import request from '../../api/request'
import { mapGetters } from 'vuex'
export default {
  name: 'Chat',
  data() {
    return {
      userName: '',
      avatar: '',
      userlist: {
        // Admin: [], // 管理员(博主)
        // members: [], // 会员(已经注册)
        // tourists: [], // 游客
      },
      groupName: {
        Admin: '博主',
        members: '会员',
        tourists: '游客'
      },
      group: {
        chatType: 'Group',
        photo: './images/group2.png',
        name: '群聊'
      },
      comments: '',
      message: '',
      showEmoji: false,
      chatID: {
        chatType: 'group',
        user: null
      },
      show: false,
      showMenu: false,
      selectClass: '',
      selectItem: '', // 存储右键选择的用户
      textarea: '',
      tab: 'chat',
      keyword: '',
      privateChat: [],
      dialogue: [],
      top: 0,
      left: 0,
      attention: false,
      type: 'chat'
    }
  },
  components: {
    Emoji
  },
  watch: {
    chatID: {
      deep: true,
      handler: function (newV, oldV) {
        this.chatID = newV
      }
    }
    // userlist: {
    //   deep: true,
    //   handler: function(newV, oldV) {
    //     this.userlist = newV
    //   },
    // },
    // dialogue: {
    //   deep: true,
    //   handler: function(newV, oldV) {
    //     this.dialogue = newV
    //   },
    // },
  },
  computed: {
    ...mapGetters([
      'getUser',
      'getGroupChat',
      'getPrivateChat',
      'getToken',
      'getOnlineUsers',
      'getMute'
    ])
  },
  async created() {
    this.$store.commit('updatePath', '/chatroom')
    if (!this.getToken) {
      this.$router.push('/')
    } else {
      this.getAlluser()
      this.obtainGroupChat()
      this.getDialogue()
    }

    this.$EventBus.$on('addMsg', (data) => {
      this.privateChat.push(data)
    })
    this.$EventBus.$on('refresh', () => {
      this.getAlluser()
    })
    this.$EventBus.$on('updateDialogue', (data) => {
      if (this.dialogue.length > 0) {
        let index = this.dialogue.findIndex(
          (item) => item.account == data.account
        )
        if (index > -1) {
          let unRead = this.dialogue[index].unRead
          this.dialogue.splice(index, 1)
          this.dialogue.unshift({
            account: data.account,
            chatType: data.chatType,
            type: data.type,
            message: data.message,
            date: data.date,
            photo: data.photo,
            userName: data.name,
            unRead: unRead + 1
          })
        } else {
          this.dialogue.unshift({
            account: data.account,
            chatType: data.chatType,
            type: data.type,
            message: data.message,
            date: data.date,
            photo: data.photo,
            userName: data.name,
            unRead: 1
          })
        }
      } else {
        this.dialogue.push({
          account: data.account,
          chatType: data.chatType,
          type: data.type,
          message: data.message,
          date: data.date,
          photo: data.photo,
          userName: data.name,
          unRead: 1
        })
      }
    })
  },
  mounted() {
    // setTimeout(() => {}, 100)
    document.oncontextmenu = function () {
      event.returnValue = false
    }
  },
  methods: {
    listen(event) {
      if (event.keyCode === 13) {
        this.send() // 发送文本
        event.preventDefault() // 阻止浏览器默认换行操作
        return false
      }
    },
    // 显示个人信息
    eventClick(e) {
      let myclass = e.target.classList[0]
      if (myclass == 'avatar_url') {
        this.show = !this.show
      } else if (myclass == 'prefix_class') {
        this.show = true
      } else {
        this.show = false
      }
      if (myclass != this.selectClass) {
        this.showMenu = false
      }
    },
    // 关闭
    close() {
      this.$router.push('/')
    },
    // 添加表情
    appendEmoji(emoji) {
      this.textarea = this.textarea + emoji
      this.showEmoji = false
      let input_dom = document.getElementById('msg_input')
      input_dom.focus()
    },
    // 发送信息
    send() {
      if (this.getMute) {
        this.$notify({
          title: '警告',
          message: '您已被禁言,无法执行该操作',
          type: 'warning'
        })
        return
      }
      if (this.textarea == '') {
        this.$notify({
          title: '警告',
          message: '不能发送空白信息',
          type: 'warning'
        })
      } else {
        let date = new Date()
        if (this.chatID.chatType == 'group') {
          this.$socket.emit('sendMsg', {
            message: this.textarea,
            name: this.getUser.userName,
            photo: this.getUser.photo,
            chatType: this.chatID.chatType,
            token: this.getToken,
            isAdmin: this.getUser.isAdmin,
            date,
            type: 'text'
          })
        } else {
          this.$socket.emit('sendMsg', {
            message: this.textarea,
            account: this.chatID.user.account,
            chatType: this.chatID.chatType,
            token: this.getToken,
            date,
            type: 'text',
            photo: this.getUser.photo,
            name: this.getUser.userName
          })
          this.privateChat.push({
            account: this.getUser.account,
            date,
            message: this.textarea,
            type: 'text'
          })
          this.$store.commit('updatePrivateChat', {
            account: this.chatID.user.account,
            msg_list: [
              {
                account: this.getUser.account,
                date,
                message: this.textarea,
                type: 'text'
              }
            ]
          })
        }
        this.textarea = ''
      }
    },
    // 发送图片
    selectFile(event) {
      this.$notify({
        title: '警告',
        message: '发送图片信息的功能还在开发中......',
        type: 'warning'
      })
      return
      let file = event.target.files[0]
      var reader = new FileReader()
      reader.readAsDataURL(file) // 读出 base64
      if (this.getMute) {
        this.$notify({
          title: '警告',
          message: '您已被禁言,无法执行该操作',
          type: 'warning'
        })
        return
      }
      reader.onloadend = () => {
        // 图片的 base64 格式, 可以直接当成 img 的 src 属性值
        var dataURL = reader.result
        if (this.chatID.chatType == 'group') {
          this.$socket.emit('sendMsg', {
            message: dataURL,
            name: this.getUser.userName,
            photo: this.getUser.photo,
            chatType: 'group',
            token: this.getToken,
            date: new Date(),
            type: 'image'
          })
        } else {
          this.$socket.emit('sendMsg', {
            message: dataURL,
            account: this.chatID.user.account,
            chatType: 'private',
            token: this.getToken,
            date: new Date(),
            type: 'image'
          })
          this.privateChat.push({
            message: dataURL,
            account: this.getUser.account,
            date: new Date(),
            type: 'image'
          })
          // 将图片信息推送到vuex中
          this.$store.commit('updatePrivateChat', {
            account: this.chatID.user.account,
            msg_list: [
              {
                message: dataURL,
                account: this.getUser.account,
                date: new Date(),
                type: 'image'
              }
            ]
          })
        }
      }
    },
    // 切换用户聊天
    async changeChat(type, info) {
      this.chatID.chatType = type
      this.chatID.user = info
      if (type == 'private') {
        this.$store.commit('changeChatId', this.chatID.user.account)
        if (!this.getPrivateChat[this.chatID.user.account]) {
          let res = await request({
            url: '/chat/obtain',
            data: {
              chatType: 'private',
              account: info.account,
              token: this.getToken
            },
            method: 'get'
          })
          if (res.msg_list && res.msg_list.length > 0) {
            this.privateChat = []
            this.privateChat.push(...this.handlingtime(res.msg_list))
            this.$store.commit('updatePrivateChat', {
              account: info.account,
              msg_list: res.msg_list
            })
          } else {
            this.privateChat = []
          }
        } else {
          this.privateChat = []
          this.privateChat.push(
            ...this.handlingtime(this.getPrivateChat[this.chatID.user.account])
          )
        }
      } else {
        this.$store.commit('changeChatId', 0)
      }
    },
    // 获取所有的用户
    async getAlluser() {
      let res = await request({
        url: '/user/findAll',
        data: {},
        method: 'get'
      })
      if (res.length > 1) {
        this.userlist = {}
        this.getUser.isAdmin ? '' : (this.userlist = { Admin: [] })
        res.forEach((item) => {
          item.chatType = 'private'
          if (item.isAdmin) {
            this.userlist.Admin ? this.userlist.Admin.push(item) : ''
          } else if (item.isTourists) {
            if (this.getUser.isAdmin) {
              if (!this.userlist.tourists) {
                this.userlist.tourists = []
              }
              this.userlist.tourists.push(item)
            }
          } else {
            if (this.getUser.isAdmin) {
              if (!this.userlist.members) {
                this.userlist.members = []
              }
              this.userlist.members.push(item)
            }
          }
        })
      }
    },
    // 获取群聊聊天记录
    async obtainGroupChat() {
      let groupChat = await request({
        url: '/chat/obtain',
        data: {
          chatType: 'group'
        },
        method: 'get'
      })
      this.$store.commit('updateGroupChat', groupChat.msg_list)
    },
    // 获取会话表
    async getDialogue() {
      let res = await request({
        url: '/dialogue/obtain',
        data: {
          token: this.getToken
        },
        method: 'get'
      })
      this.dialogue = res
    },
    // 处理信息时间
    handlingtime(arr) {
      // 遍历更改时间，当两条信息发送的时间间隔不超过指定时间时则将时间修改为‘’
      let prev = null //前一条信息的发送时间
      let current = null //后一条信息的发送时间
      let distant = null //时间差
      for (var i = 1; i < arr.length; i++) {
        prev = new Date(arr[i - 1].date).getTime()
        current = new Date(arr[i].date).getTime()
        distant = (current - prev) / 1000 / 60
        distant >= 2 ? (arr[i].showTime = true) : (arr[i].showTime = false)
      }
      arr[0].showTime = true
      return arr
    },
    // 右键菜单
    Menu(e, item) {
      // 管理员才有权限操作
      if (this.getUser.isAdmin) {
        this.selectClass = e.target.classList[0]
        this.showMenu = true
        this.top = e.clientY + 'px'
        this.left = e.clientX + 'px'
        this.selectItem = item
      }
    },
    // 关于禁言的事件
    async mute() {
      let res = await request({
        url: '/user/mute',
        data: {
          account: this.selectItem.account
        },
        method: 'post'
      })
      if (res.status) {
        this.$notify({
          title: '成功',
          message: '操作成功',
          type: 'success'
        })
        this.getAlluser()
      } else {
        this.$notify.error({
          title: '错误',
          message: '操作失败'
        })
      }
      this.showMenu = false
    },
    open() {
      this.attention = true
    },
    goMusic() {
      this.$router.push('/musichome')
    }
  },
  updated() {
    // 页面更新时让滚动条保持在最底部
    this.$refs.chatScroll.$refs.vs.scrollTo({
      y: '100%'
    })
  },
  beforeDestroy() {
    this.$store.commit('changeChatId', 0)
  }
}
</script>
<style lang="scss" scoped>
@import './chat.scss';
</style>
